<?php
	
	/**
	 * 生成reset的请求URL
	 */
	function createRestUrl($action,$map,$method="get"){
	
		$row['app_id']   = C("APP_ID");
		$row['timestamp']= time();
		$row['l']        = getLang();
	
		$arr   = array_merge($map,$row);
		$url   = http_build_query($arr);
	
		$arr['app_key']  = C("APP_KEY");
		$_sign = createRestSign($arr);
	
		if($method == "post"){
			$url = http_build_query($row);
		}
		return C('APP_REST').$action."&".$url."&_sign=".$_sign;
	}
	
	
	//后台表单自动回复Tab
	function formReplyTab($arg){
		$html = '';
		if(C('WECHAT_OPEN')){
			$html .= '<li>';
			$html .= '<a href="#tab_reply" data-toggle="tab">';
			$html .= L('cfg_form_tab_wechat_reply');	
			$html .= '</a>';
			$html .= '</li>';
		}
		
		echo $html;		
	}
	
	//后台表单自动回复表单
	function formReplyEle($arg){
		$html = '';
		if(C('WECHAT_OPEN')){
			$html .= '<div class="tab-pane" id="tab_reply">';
			$html .= '<div class="row-fluid">';
			$html .= '<div class="span6">';
			$html .= '<button type="button" id="btn_addReply" class="btn blue">';
			$html .= '<i class="icon-plus"></i>';
			$html .= L('cfg_form_wechat_reply_add');
			$html .= '</button>';
			$html .= '<button type="button" id="btn_refresh" class="btn green  icn-only">';
			$html .= '<i class="icon-refresh"></i>';
			$html .= '</button>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '<div class="clear" style="height:10px;"></div>';
			$html .= '<table class="table table-striped table-bordered table-hover table-condensed flip-content">';
			$html .= '<thead>';
			$html .= '<tr class="list_head ct" style="text-align:center">';
			$html .= '<td>'.L('cfg_form_reply_type').'</td>';
			$html .= '<td>'.L('cfg_form_wechat_reply_type').'</td>';
			$html .= '<td >'.L('cfg_form_wechat_reply_explain').'</td>';
			$html .= '<td>'.L('cfg_form_ele_opreate').'</td>';
			$html .= '</tr>';
			$html .= '</thead>';
			$html .= '<tbody id="tableList">';
			$html .= '</tbody>';
			$html .= '</table>';
			$html .= '</div>';
		}
		
		echo $html;		
	}
	
	//后台表单自动回复JS
	function formReplyJs($arg){
		$html = '';
		if(C('WECHAT_OPEN')){
			$html .= '<script src="'.TMPL_URL.C('DEFAULT_THEME').'/Assets/scripts/wechat/list.js"></script>';
			$html .= '<script type="text/javascript">';
			$html .= 'jQuery(document).ready(function() {';
			
			//新增回复
			$html .= '$(\'#btn_addReply\').on(\'click\',function(){';
			$html .= 'var table   = "Article";';
			$html .= 'var solevar = $("input[name=solevar]").val();';
			$html .= 'art.dialog.open(\''.U("/Reply/content_add").'\'+\'&solevar=\'+solevar+\'&table=\'+table,{title: "'.L('cfg_form_wechat_reply_add').'", width:600,height:420,fixed:true,top:60});';
			$html .= '});';
			
			//刷新回复
			$html .= '$(\'#btn_refresh\').on(\'click\',function(){';
			$html .= 'getListReply();';
			$html .= '});';
			
			//删除回复
			$html .= '$(\'.delAlone\').live(\'click\',function(){';
			$html .= '$.get(\''.U("/Reply/delcont").'\'+\'&id=\'+$(this).attr(\'data-id\'));';
			$html .= 'getListReply();';
			$html .= '});';
			
			
			//获取初始回复
			$html .= 'getListReply();';
			
			//获取回复列表
			$html .= 'function getListReply(){';
			$html .= '$(\'#tableList\').html(\'<tr><td colspan="3"><div id="ajaxLoadingIco" style="text-align:center;padding:20px;">\'+\'<img src="\'+ABS_URL_Theme+\'/Assets/img/ajax-loading.gif"/></div></td></tr>\');';
			$html .= 'var solevar = $(\'input[name=solevar]\').val();';
			$html .= 'var parameter = {};';
			$html .= 'parameter.url = \''.U("/Reply/content_reply").'\'+\'&solevar=\'+solevar;';
			$html .= 'parameter.listId = \'tableList\';';
			$html .= 'wechatList.init(parameter);';		
			$html .= '}';
			
			$html .= '});';
					
			$html .= '</script>';
		}
		
		echo $html;		
	}
	
	//后台表单多站点选项支持
	function eleSiteShow($arg){
		$html = '';		
		echo $html;		
	}
	
	//后台表单多终端选项支持
	function eleDeviceShow($arg=''){
		$html = '';
		
		if(count(C('MOREDEVICE_LIST'))>1){
			$html .= '<div class="control-group">';
			$html .= '<label class="control-label">'.L('cfg_form_ele_device').' <span class="required">*</span></label>';
			$html .= '<div class="controls">';
			foreach(C('MOREDEVICE_LIST') as $k=>$v){
				$checked = '';
				if(strpos('|'.$arg,$k)){
					$checked = 'checked="checked"';
				}else{
					if($v[1]=='checked'){
						$checked = 'checked="checked"';
					}	
				}
				$html .= '<input '.$checked.' type="checkbox" name="device[]" value="'.$k.'"/> '.L($v[0]).'　　';
			}
			$html .= '</div>';
			$html .= '</div>';
		}else{
			foreach(C('MOREDEVICE_LIST') as $k=>$v){
				$html .= '<input type="hidden" value="'.$k.'" name="device">';
			}
		}
		
		echo $html;		
	}
	
	//后台表单多国语言项控制
	function eleLangShow($arg){
		$html = '';
		if(count(C('LANG_ARRAY'))>1){
			$html .= '<div class="control-group">';
			$html .= '<label class="control-label">'.L('cfg_form_ele_lang').' <span class="required">*</span></label>';
			$html .= '<div class="controls">';
			$html .= '<select name="lang" class="span6 m-wrap">';
			$html .= '<option value="">'.L('cfg_form_tis_select').'</option>';
			foreach(C('LANG_ARRAY') as $k=>$v){
				if($k==$arg){
					$html .= '<option selected value="'.$k.'">'.$v.'</option>';
				}else{
					$html .= '<option value="'.$k.'">'.$v.'</option>';
				}
			}
			$html .= '</select>';
			$html .= '</div>';
			$html .= '</div>';
		}else{
			$html .= '<select name="lang" class="span6 m-wrap" style="display:none">';
			foreach(C('LANG_ARRAY') as $k=>$v){
				if($k==$arg){
					$html .= '<option selected value="'.$k.'">'.$v.'</option>';
				}else{
					$html .= '<option value="'.$k.'">'.$v.'</option>';
				}
			}
			$html .= '</select>';
		}
		
		echo $html;		
	}
	
	//后台列表多终端搜索选项控制
	function listDeviceShow($arg){
		$html = '';
		if(count(C('MOREDEVICE_LIST'))>1){
			$html .= '<select name="device" id="device" class="span3 m-wrap">';
			$html .= '<option value="">'.L('cfg_form_ele_nolimit').'</option>';
			foreach(C('MOREDEVICE_LIST') as $k=>$v){
				if($k==$arg){
					$html .= '<option selected value="'.$k.'">'.L($v[0]).'</option>';
				}else{
					$html .= '<option value="'.$k.'">'.L($v[0]).'</option>';
				}
			}
			$html .= '</select>';
		}else{
			foreach(C('MOREDEVICE_LIST') as $k=>$v){
				$html .= '<input type="hidden" value="'.$k.'" name="device" id="device">';
			}
		}
		
		echo $html;		
	}
	
	//后台列表多国语言项控制
	function listLangShow($arg){
		$html = '';
		if(count(C('LANG_ARRAY'))>1){
			$html .= '<div id="lang_filter" class="span5">';
			$html .= '<div class="btn-group">';
			$html .= '<a href="javascript:;" title="" class="btn red">All</a>';
			foreach(C('LANG_ARRAY') as $k=>$v){
				$html .= '<a href="javascript:;" title="'.$k.'" class="btn">'.$v.'</a>';
			}
			$html .= '</div>';
			$html .= '</div>';
		}else{
			$html .= '<div id="lang_filter" class="span5">';
			$html .= '<div class="btn-group">';
			foreach(C('LANG_ARRAY') as $k=>$v){
				$html .= '<a href="javascript:;" title="'.$k.'" class="btn red">'.$v.'</a>';
			}
			$html .= '</div>';
			$html .= '</div>';
		}
		
		echo $html;
	}
	
	//百度POI表的列操作
	function mapColumn($data=array(),$func='create'){
		
		$data['name'] = "门店编号";
		$data['key']  = "outletid";
		/* $data['name'] = "城市编号";
		$data['key']  = "city"; */
		$data['type'] = 1;
		$data['max_length'] = 11;
		$data['is_sortfilter_field'] = 0 ;
		$data['is_search_field'] = 0 ;
		$data['is_index_field']  = 0 ;
		
		$map['ak']  = C("MAP_AK");
		$map['geotable_id'] = C("MAP_OUTLET_ID");
		
		$url = C("MAP_COLUMN").$func;
		$map = array_merge($map,$data);
		return curlPost($url,$map);
	}
	
	//云存储百度POI
	function mapStorge($data,$func='create'){
		
		$map['ak']  = C("MAP_AK");
		$map['geotable_id'] = C("MAP_OUTLET_ID");
		$map['coord_type']  = 3; 
		
		$url  = C("MAP_STORGE").$func;
		$map  = array_merge($map,$data);
		$json = curlPost($url,$map);
		//dump($map);dump($json);exit();
		return $json;
	}
	

	//返回json对应语言包值
	function dejsonByLang($value,$lang=''){
		if(empty($lang)){
			$lang = getLang();
		}
		$value   = json_decode($value,true);
		$val     = '';
		if(isset($value[$lang])){
			$val = $value[$lang];
		}
		return $val;
	}
	
	function create_back_menu($menu,$lang,$menuid,$nowId){
		$html = "" ;
		foreach($menu as $one){
			if($one['level'] == 1 && $one['status'] == 1){
				$html .= '<li class=""><a href="#" target=""><i class="'.$one['icon'].'"></i>';
				$html .= '<span class="title">'.dejsonByLang($one["value"],$lang).'</span><span class="arrow"></span></a>';
				$str   = "" ;
				foreach($menu as $two){
					if($one['id'] == $two['pid'] && $two['status'] == 1){
						$active = ($two['id']==$nowId) ? "active" : "";
						$str .= '<li class="'.$active.'"><a href="'.U($two['url'],array($menuid=>$two['id'])).'" target=""><i class="'.$two['icon'].'"></i>';
						$str .= '<span class="title">'.dejsonByLang($two["value"],$lang).'</span><span></span></a></li>';
					}
				}
				if($str){
					$html .= '<ul class="sub-menu">'.$str.'</ul>';
				}
				$html .= '</li>';
			}
		}
		return $html;
	}

	//模块得到数组的select
	function get_select_module($arr,$fid,$nid,$module,$prefix=''){
		$html = '';
		if(is_array($arr)){
			foreach($arr as $k=>$value){
				$mod = $value['module'];
				$tag = $value["tag"];
				$dis = ($value['module'] == $module) ? "": "disabled";
				if($value['pid']==$fid) {
					if($nid==$value['id']){
						$html .= "<option value='".$value['id']."' tag='".$tag."' selected $dis m='$mod'>".$prefix." ".$value['title']."</option>";
					}else{
						$html .= "<option value='".$value['id']."' tag='".$tag."' $dis m='$mod'>".$prefix." ".$value['title']."</option>";
					}
					$html .= get_select_module($arr,$value['id'],$nid,$module,$prefix."—");
				}
			}
		}
		return $html;
	}
	
	//获取对应内容的缩略图
	function get_content_thumb($solevar,$field='single',$flag=true){
		$image = find_thumb($solevar,$field);
		if($image['id']){
			$url = $image['fileurl'];
		}else{
			if($flag){
				$url = get_syscfig_key("wxsmallpic","url");
			}else{
				$url = get_syscfig_key("wxbigpic","url");
			}
		}
		return ABS_URL.UPLOAD_URL.$url;
	}
	
	//根据不同内容生成对应的URL
	function get_content_url($table,$array){
		$front = C("WECHAT_URL");
		$base  = ABS_URL.$front;
		$url   = $array['url'];
		if($url){
			$wechat  = $base.$url;
			$pattern = '/(http|https|ftp|file){1}(:\/\/)?([\da-z-\.]+)\.([a-z]{2,6})([\/\w \.-?&%-=]*)*\/?/';
			if(preg_match($pattern,$url)){
				$pattern = "/\\?/";
				$wechat  = $url."";
				if(!preg_match($pattern,$url)){
					$wechat  = $url."?1=1";
				}  
			}
			$handurl = $array['handurl'];
			if($handurl){
				$wechat  = $base.$handurl;
				if(preg_match($pattern,$handurl)){
					$pattern = "/\\?/";
					$wechat  = $handurl;
					if(!preg_match($pattern,$url)){
						$wechat  = $url."?1=1";
					}
				}	
			}
		}else{
		    $wechat = $base.$table.'/detail/id/'.$array['id'];
		}
		return $wechat;
	}
	
	
	//得到栏目的名称
	function get_cate_name($id,$lang){
		$name = '';
		if($id&&$lang){
			$cates = F('cate_'.$lang);
			if(empty($cates)){
				$data  = D("Category");
				$cates = $data->getCateByModule($lang);
			}
			$name  = $cates[$id]['title'];
		}
		return $name;
	}

	/**
	 *  更新内容对应的回复
	 *  array(title content_solevar)
	 *  flag true(add,update) false(del)
	**/
	function create_reply_content($array,$flag=true){
		if(is_array($array)){
			$content_solevar = $array['solevar'];
			$content_title   = $array['title'];
		}elseif(is_object($array)){
			$content_solevar = $array->solevar;
			$content_title   = $array->title;	
		}
		
		$data['title']   = $content_title ;

		$reply   = D("Reply");
		$content = D("ReplyContent");
		$lists   = $content->contentByContentSolevar($content_solevar);
	
		foreach($lists as $v){
			if($flag){
				$data['id'] = $v['id'];
				$content->save($data);
			}else{
				$content->delete($v['id']);
			}
			
			$reply_solevar = $v['reply_solevar']; 
			$rows  = $reply->replyBySolevar($reply_solevar);
			if($rows['id']){
				$funcs = "cache_reply_".$rows['retype'];
				$content->$funcs($v['reply_solevar']);
			}
		}
	}
	
	/**
	 * URL组装 支持不同URL模式
	 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
	 * @param string|array $vars 传入的参数，支持数组和字符串
	 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
	 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
	 * @param boolean $domain 是否显示域名
	 * @return string
	 */
	function U($url='',$vars='',$suffix=true,$redirect=false,$domain=false) {
		// 解析URL
		$info   =  parse_url($url);
		$url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
		if(isset($info['fragment'])) { // 解析锚点
			$anchor =   $info['fragment'];
			if(false !== strpos($anchor,'?')) { // 解析参数
				list($anchor,$info['query']) = explode('?',$anchor,2);
			}
			if(false !== strpos($anchor,'@')) { // 解析域名
				list($anchor,$host)    =   explode('@',$anchor, 2);
			}
		}elseif(false !== strpos($url,'@')) { // 解析域名
			list($url,$host)    =   explode('@',$info['path'], 2);
		}
		// 解析子域名
		if(isset($host)) {
			$domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
		}elseif($domain===true){
			$domain = $_SERVER['HTTP_HOST'];
			if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
				$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
				// '子域名'=>array('项目[/分组]');
				foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
					if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
						$domain = $key.strstr($domain,'.'); // 生成对应子域名
						$url    =  substr_replace($url,'',0,strlen($rule[0]));
						break;
					}
				}
			}
		}
	
		// 解析参数
		if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
			parse_str($vars,$vars);
		}elseif(!is_array($vars)){
			$vars = array();
		}
		if(isset($info['query'])) { // 解析地址里面参数 合并到vars
			parse_str($info['query'],$params);
			$vars = array_merge($params,$vars);
		}
	
		// URL组装
		$depr = C('URL_PATHINFO_DEPR');
		if($url) {
			if(0=== strpos($url,'/')) {// 定义路由
				$route      =   true;
				$url        =   substr($url,1);
				if('/' != $depr) {
					$url    =   str_replace('/',$depr,$url);
				}
			}else{
				if('/' != $depr) { // 安全替换
					$url    =   str_replace('/',$depr,$url);
				}
				// 解析分组、模块和操作
				$url        =   trim($url,$depr);
				$path       =   explode($depr,$url);
				$var        =   array();
				$var[C('VAR_ACTION')]       =   !empty($path)?array_pop($path):ACTION_NAME;
				$var[C('VAR_MODULE')]       =   !empty($path)?array_pop($path):MODULE_NAME;
				if($maps = C('URL_ACTION_MAP')) {
					if(isset($maps[strtolower($var[C('VAR_MODULE')])])) {
						$maps    =   $maps[strtolower($var[C('VAR_MODULE')])];
						if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){
							$var[C('VAR_ACTION')] = $action;
						}
					}
				}
				if($maps = C('URL_MODULE_MAP')) {
					if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){
						$var[C('VAR_MODULE')] = $module;
					}
				}
				if(C('URL_CASE_INSENSITIVE')) {
					$var[C('VAR_MODULE')]   =   parse_name($var[C('VAR_MODULE')]);
				}
				if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
					if(!empty($path)) {
						$group                  =   array_pop($path);
						$var[C('VAR_GROUP')]    =   $group;
					}else{
						if(GROUP_NAME != C('DEFAULT_GROUP')) {
							$var[C('VAR_GROUP')]=   GROUP_NAME;
						}
					}
					if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
						$var[C('VAR_GROUP')]    =  strtolower($var[C('VAR_GROUP')]);
					}
				}
			}
		}
	
		if(C('URL_MODEL') == 0) { // 普通模式URL转换
			$url        =   __APP__.'?'.http_build_query(array_reverse($var));
			if(!empty($vars)) {
				$vars   =   urldecode(http_build_query($vars));
				$url   .=   '&'.$vars;
			}
		}else{ // PATHINFO模式或者兼容URL模式
			if(isset($route)) {
				$url    =   __APP__.'/'.rtrim($url,$depr);
			}else{
				$url    =   __APP__.'/'.implode($depr,array_reverse($var));
			}
			if(!empty($vars)) { // 添加参数
				foreach ($vars as $var => $val){
					if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
				}
			}
			if($suffix) {
				$suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
				if($pos = strpos($suffix, '|')){
					$suffix = substr($suffix, 0, $pos);
				}
				if($suffix && '/' != substr($url,-1)){
					$url  .=  '.'.ltrim($suffix,'.');
				}
			}
		}
		if(isset($anchor)){
			$url  .= '#'.$anchor;
		}
		if($domain) {
			$url   =  (is_ssl()?'https://':'http://').$domain.$url;
		}
		if($redirect) // 直接跳转URL
			redirect($url);
		else
			return $url;
	}
	
	function getProductStatus($status){
		$html = "";
		if($status){
			if($status==1){
				$html = L('cfg_form_ele_recommend');
			}elseif($status==2){
				$html = L('cfg_form_ele_hot');
			}elseif($status==3){
				$html = L('cfg_form_ele_new');
			}elseif($status==4){
				$html = L('cfg_form_ele_promotions');
			}
		}else{
			$html = "";
		}
		return $html;
	}
	
   
?>